//
//  SCCarImageEditViewController.m
//  Shuaiche
//
//  Created by dangshuai on 2019/4/23.
//  Copyright © 2019 zzs. All rights reserved.
//

#import "SCCarImageEditViewController.h"
#import "SCCarAddImageModel.h"
#import "SCLabelItemCell.h"
//#import "SCCarImagePasterView.h"
#import "SCPasterView.h"
#import "SCMenuView.h"
#import <Photos/Photos.h>
#import "MBProgressHUD+Add.h"
#import <QuartzCore/QuartzCore.h>
#import "UIView+Quadrilateral.h"
#import <CoreImage/CoreImage.h>
#import <CoreImage/CoreImageDefines.h>
#import <CoreImage/CIFilterConstructor.h>
#import "SCSysHelper.h"

@interface SCCarImageEditViewController ()<UICollectionViewDataSource,UICollectionViewDelegate, UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeight;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *actionView;


@property (nonatomic, strong) UIImageView *editImageView;
//@property (nonatomic, strong) SCCarImagePasterView *pasterView;
@property (nonatomic, strong) SCPasterView *carPasterView;
//@property (nonatomic, strong) UIView *scaleView;
@property (nonatomic, assign) BOOL hasProcess;
@property (nonatomic, strong) NSIndexPath *selectIndex;
@property (nonatomic ,strong) UIView *topLeftControl,*topRightControl,*bottomLeftControl,*bottomRightControl;
//@property (nonatomic, strong) CAShapeLayer *borderLayer;
//@property (nonatomic, strong) UIBezierPath *borderPath;
@property (weak, nonatomic) IBOutlet UISlider *scaleSlider;
//@property (weak, nonatomic) IBOutlet UISlider *rotateSlider;

@property (nonatomic, assign) CGFloat preZoomScale;
@property (nonatomic, assign) CGFloat lastSilderValue;
@property (nonatomic, assign) CGPoint centerPoint;

@end
static NSString *cellUse = @"cell";
static const CGFloat kControlWidth = 18;
@implementation SCCarImageEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"图片编辑";
    self.view.backgroundColor = SC_RGB(34, 34, 34);
    _preZoomScale = 1;
    _lastSilderValue = 1;
    [self createRightItems];
    [self setUpSubviews];
    _bottomViewHeight.constant = kSCScreenBottomOffset + 110;
    _scrollViewTop.constant = kSCNavigationHeight;
    
    if (_groupNameArray.count > 0) {
        _bottomView.hidden = NO;
        _actionView.hidden = NO;
        [self.collectionView registerNib:[UINib nibWithNibName:@"SCLabelItemCell" bundle:nil] forCellWithReuseIdentifier:cellUse];
        UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
        layout.estimatedItemSize = CGSizeMake(100, 36);
    }
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    if (_editImage.size.width >= _editImage.size.height) {
        _editImageView.center = CGPointMake(kSCScreenWidth/2.f, CGRectGetMidY(_imageScrollView.bounds));
    } else {
        if (CGRectGetHeight(_editImageView.bounds) < CGRectGetHeight(_imageScrollView.bounds)) {
            _editImageView.center = CGPointMake(kSCScreenWidth/2.f, CGRectGetMidY(_imageScrollView.bounds));
        } else {
            _editImageView.center = CGPointMake(kSCScreenWidth/2.f, CGRectGetMidY(_editImageView.bounds));
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 60, 40);
  
    [backBtn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backEvent) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
  
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -45, 0, 0);
  if (@available(iOS 15.0, *)) {
      UINavigationBarAppearance *apperance = [UINavigationBarAppearance new];
      apperance.backgroundColor = [UIColor clearColor];
      apperance.backgroundEffect = nil;
      apperance.shadowColor = nil;
      apperance.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
//      [apperance setBackIndicatorImage:[UIImage imageNamed:@"back_icon"] transitionMaskImage:[UIImage imageNamed:@"back_icon"]];
      self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
      self.navigationController.navigationBar.standardAppearance = apperance;
  } else {
      //背景色
      [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
      
      [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
  }
  self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
  [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//    [self showNavbarLine:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self popGestureEnable: YES];
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *apperance = [[UINavigationBarAppearance alloc]init];
        [apperance configureWithOpaqueBackground];// 重置背景和阴影颜色
        apperance.backgroundColor = [UIColor whiteColor];
        apperance.backgroundEffect = nil;
        apperance.shadowColor = nil;
        // 去除导航栏阴影（如果不设置clear，导航栏底下会有一条阴影线）
        apperance.shadowColor =  [UIColor clearColor];
        [apperance setBackIndicatorImage:[UIImage imageNamed:@"back_icon"] transitionMaskImage:[UIImage imageNamed:@"back_icon"]];
        apperance.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
        [self.navigationController.navigationBar setStandardAppearance:apperance];
        [self.navigationController.navigationBar setScrollEdgeAppearance:apperance];
    } else {
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    }
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    [SCSysHelper changeStatusBarStyle:UIStatusBarStyleDefault];
//    [self showNavbarLine:YES];
}

#pragma mark - backEvent
-(void)backEvent {
  [self.navigationController popViewControllerAnimated:YES];
}

- (void)createRightItems {
    UIBarButtonItem *menu = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"edit_nav_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(menuButtonClick:)];
    UIBarButtonItem *save = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"edit_nav_save"] style:UIBarButtonItemStylePlain target:self action:@selector(saveButtonClick)];
    self.navigationItem.rightBarButtonItems = @[save,menu];
}

- (void)menuButtonClick:(UIBarButtonItem *)sender {
    SCMenuView *menuView = [SCMenuView menuWithTitles:@[@"设为主图",@"保存到本地",@"删除"]
                                           withHandle:^(NSInteger idx) {
                                               if (idx == 0) {
                                                   self.toMainPicBlock();
                                                   [MBProgressHUD showSuccess:@"设置成功" toView:nil];
                                               } else if (idx == 1) {
                                                   [self writePhotoAlume];
                                               } else {
                                                   [self deleteImage];
                                               }
    }];
    menuView.frame = CGRectMake(kSCScreenWidth - 155, kSCNavigationHeight, 90, 118);
    [menuView show];
}

- (void)saveButtonClick {
    UIImage *image = [self processImage];
    self.editImageView.image = image;
    self.reloadBlock(image,_hasProcess);
    [self.navigationController popViewControllerAnimated:YES];
    _carPasterView.pasterImage = nil;
    self.carPasterView.hidden = YES;
}

- (void)deleteImage {
    self.deleteBlock();
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)writePhotoAlume {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"暂无相册权限,保存失败" toView:nil];
            });
            return;
        }
    }];
    
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"正在保存" toView:nil];
    UIImage *image = [self processImage];
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setPointControlHidden:NO];
//            self.borderLayer.path = self.borderPath.CGPath;
            if (error) {
                [hud switchShowError:error.localizedDescription];
            } else {
                [hud switchShowSuccess:@"保存成功"];
            }
        });
        
    }];
}

- (UIImage *)processImage {
    UIImage *paster = _carPasterView.pasterImage;
    if (!paster) {
        return _editImage;
    }
    _hasProcess = YES;
//    self.borderLayer.path = nil;

//    _borderLayer.lineWidth = 0.0f;
    [self setPointControlHidden:YES];

    CGSize size = _editImageView.image.size;
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);
    if ([self.editImageView drawViewHierarchyInRect:CGRectMake(0, 0, size.width, size.height) afterScreenUpdates:YES]) {
        [self.editImageView drawViewHierarchyInRect:CGRectMake(0, 0, size.width, size.height) afterScreenUpdates:YES];
    }
    CGFloat scale = _editImageView.image.size.width/_editImageView.bounds.size.width;
    CGContextScaleCTM(UIGraphicsGetCurrentContext(),scale , scale);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//CIFilter生成图片
- (UIImage *)imageByTransformingImage:(UIImage *)image {

    if (image == nil) {
        return nil; //image not found
    }
    CIImage *coreImage = [CIImage imageWithData:UIImagePNGRepresentation(image)];

    if (!coreImage) {
        return nil; // image is not converted in core image
    }

    CIFilter *perspectiveTransformation = [CIFilter filterWithName:@"CIPerspectiveTransform"];
    [perspectiveTransformation setValue:[CIVector vectorWithCGPoint:_topLeftControl.center] forKey:@"inputTopLeft"];
    [perspectiveTransformation setValue:[CIVector vectorWithCGPoint:_topRightControl.center] forKey:@"inputTopRight"];
    [perspectiveTransformation setValue:[CIVector vectorWithCGPoint:_bottomRightControl.center] forKey:@"inputBottomRight"];
    [perspectiveTransformation setValue:[CIVector vectorWithCGPoint:_bottomLeftControl.center] forKey:@"inputBottomLeft"];
    [perspectiveTransformation setValue:coreImage forKey:kCIInputImageKey];

    CIImage *resultImage = [perspectiveTransformation outputImage];
    CIImage *wImage = [resultImage imageByApplyingOrientation:kCGImagePropertyOrientationDownMirrored];

    CIContext *ciContext = [CIContext contextWithOptions:nil];
    CGImageRef cgImageRef = [ciContext createCGImage:wImage fromRect:[wImage extent]];
    UIImage *transformedImage = [UIImage imageWithCGImage:cgImageRef];
    return transformedImage;
}

- (void)deleteThePaster {
    self.carPasterView.hidden = YES;
//    self.borderLayer.path = nil;
    [self setPointControlHidden:YES];
    [_collectionView deselectItemAtIndexPath:_selectIndex animated:YES];
}


#pragma mark- UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.groupNameArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SCLabelItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellUse forIndexPath:indexPath];
    SCCarAddImageModel *model = self.groupNameArray[indexPath.item];
    cell.textLabel.text = model.unionName;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_selectIndex != nil) {
        if (_selectIndex == indexPath) {
            [self deleteThePaster];
            _selectIndex = nil;
            return;
        }
    }
    _selectIndex = indexPath;
    SCCarAddImageModel *model = self.groupNameArray[indexPath.item];
    self.carPasterView.pasterImagePath = model.licensePlate;
    self.carPasterView.hidden = NO;
    
    [self setPointControlHidden:NO];
    [self updateTranform];
//    [self updateBorderLayer];
}

- (void)setPointControlHidden:(BOOL) isHide {
    self.topLeftControl.hidden = isHide;
    self.topRightControl.hidden = isHide;
    self.bottomLeftControl.hidden = isHide;
    self.bottomRightControl.hidden = isHide;
//    .borderLayer.hidden = isHide;

}
#pragma mark- setUpSubviews
- (void)setUpSubviews {
    _editImageView = [[UIImageView alloc]initWithImage:_editImage];
    CGFloat h = kSCScreenWidth * _editImage.size.height / _editImage.size.width;
    _editImageView.bounds = CGRectMake(0, 0, kSCScreenWidth, h);
    _editImageView.userInteractionEnabled = YES;
    _imageScrollView.delegate = self;
    _imageScrollView.bounces = NO;
    [_imageScrollView addSubview:_editImageView];
    
    _scaleSlider.minimumTrackTintColor = SC_Color_Tint;
    _scaleSlider.maximumTrackTintColor = [UIColor whiteColor];
}
- (SCPasterView *)carPasterView {
    if (!_carPasterView) {
        _carPasterView = [[SCPasterView alloc] init];
        _editImageView.userInteractionEnabled = YES;
        _editImageView.clipsToBounds = YES;
        _carPasterView.hidden = YES;
        _carPasterView.delegate = (id<SCPasterViewDelegate>)self;
        [_editImageView addSubview:_carPasterView];
        
        CGFloat w = 140;
        CGFloat h = 42;
        CGFloat x = (kSCScreenWidth-w)/2;
        CGFloat y = (_editImageView.frame.size.height-h)/2;
        self.topLeftControl = [self addControl:CGPointMake(x,y)];
        self.topRightControl = [self addControl:CGPointMake(x+w,y)];
        self.bottomLeftControl = [self addControl:CGPointMake(x,y+h)];
        self.bottomRightControl = [self addControl:CGPointMake(x+w,y+h)];
        _centerPoint = CGPointMake(x + w/2, y + h/2);
    }
    return _carPasterView;
}

//- (CAShapeLayer *)borderLayer {
//    if (!_borderLayer) {
//        _borderLayer = [[CAShapeLayer alloc] init];
//        [_borderLayer setLineWidth:1.0];
//        [_borderLayer setStrokeColor:SC_RGB(255, 156, 0).CGColor];
//        [_borderLayer setFillColor:UIColor.clearColor.CGColor];
//        _borderLayer.anchorPoint = CGPointMake(0.5, 0.5);
//        [_editImageView.layer addSublayer:_borderLayer];
//    }
//    return _borderLayer;
//}

- (UIView *)addControl:(CGPoint)p
{
    
    CALayer *layer = [[CALayer alloc] init];
    layer.backgroundColor = UIColor.whiteColor.CGColor;
    layer.bounds = CGRectMake(0, 0, 10, 10);
    layer.position = CGPointMake(kControlWidth, kControlWidth);
    layer.cornerRadius = 5;
    layer.masksToBounds = YES;
    
    CALayer *bgLayer = [[CALayer alloc] init];
    bgLayer.backgroundColor = SC_HEX(0xFFB000).CGColor;
    bgLayer.bounds = CGRectMake(0, 0, 18, 18);
    bgLayer.position = CGPointMake(kControlWidth, kControlWidth);
    bgLayer.cornerRadius = 9;
    bgLayer.masksToBounds = YES;
    
    UIView *control = [[UIView alloc] init];
    control.bounds = CGRectMake(0, 0, kControlWidth * 2, kControlWidth * 2);
    control.center = p;
    [control.layer addSublayer:bgLayer];
    [control.layer addSublayer:layer];
    [self.editImageView addSubview:control];
    UIPanGestureRecognizer *rec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragMarker:)];
    [control addGestureRecognizer:rec];
    control.hidden = YES;
    return control;
}

#pragma mark- SCPasterViewDelegate
- (void)pasterViewDidMovedWithPoint:(CGPoint)changedPoint {
    CGFloat x = changedPoint.x, y = changedPoint.y;
    self.topLeftControl.center = CGPointOffsetPoint(_topLeftControl.center, x, y);
    self.topRightControl.center = CGPointOffsetPoint(_topRightControl.center, x, y);
    self.bottomLeftControl.center = CGPointOffsetPoint(_bottomLeftControl.center, x, y);
    self.bottomRightControl.center = CGPointOffsetPoint(_bottomRightControl.center, x, y);
    [self updateTranform];
//    [self updateBorderLayer];
}

- (void)pasterViewTouchBegin {
    _imageScrollView.scrollEnabled = NO;
}

- (void)pasterViewTouchEnd {
    _imageScrollView.scrollEnabled = YES;
    [self updateCenterPoint];
}

- (void)updateCenterPoint {
    CGFloat x1 = MIN(self.bottomLeftControl.center.x, self.topLeftControl.center.x);
    CGFloat y1 = MIN(self.topLeftControl.center.y, self.topRightControl.center.y);
    CGFloat x2 = MAX(self.topRightControl.center.x, self.bottomRightControl.center.x);
    CGFloat y2 = MAX(self.bottomLeftControl.center.y, self.bottomRightControl.center.y);
    _centerPoint = CGPointMake((x1 + x2) / 2, (y1 + y2) / 2);
}

#pragma mark-
//拖动
- (void)dragMarker:(UIPanGestureRecognizer *)recognizer {

    UIView *view = [recognizer view];
    CGPoint translation = [recognizer translationInView:self.view];
    CGPoint newCenter = view.center;

    newCenter.x += (translation.x / _preZoomScale);
    newCenter.y += (translation.y / _preZoomScale);
    CGFloat margin = kControlWidth / _preZoomScale;
    if (view == self.topLeftControl) {
        if (newCenter.x >= self.topRightControl.center.x-margin ||
            newCenter.y >= self.bottomLeftControl.center.y-margin) {
            return;
        }
    }
    if (view == self.topRightControl) {
        if (newCenter.x <= self.topLeftControl.center.x+margin ||
            newCenter.y >= self.bottomRightControl.center.y-margin) {
            return;
        }
    }
    if (view == self.bottomLeftControl) {
        if (newCenter.x >= self.bottomRightControl.center.x-margin ||
            newCenter.y <= self.topLeftControl.center.y+margin) {
            return;
        }
    }
    if (view == self.bottomRightControl) {
        if (newCenter.x <= self.bottomLeftControl.center.x+margin ||
            newCenter.y <= self.topRightControl.center.y+margin) {
            return;
        }
    }
    view.center = newCenter;
    [recognizer setTranslation:CGPointZero inView:self.view];
    

    [self updateCenterPoint];
//    _scaleView.frame = CGRectMake(x1, y1, x2 - x1, y2 - y1);
    
    
    [self updateTranform];
//    [self updateBorderLayer];
}

//- (void)updateBorderLayer {
//    UIBezierPath *path = [UIBezierPath bezierPath];
//    [path moveToPoint:self.topRightControl.center];
//    [path addLineToPoint:self.topLeftControl.center];
//    [path addLineToPoint:self.bottomLeftControl.center];
//    [path addLineToPoint:self.bottomRightControl.center];
//    [path closePath];
//    self.borderPath = path;
//    self.borderLayer.path = path.CGPath;
//
//}
- (void)updateTranform {
    CGPoint tl = self.topLeftControl.center,
    tr = self.topRightControl.center,
    bl = self.bottomLeftControl.center,
    br = self.bottomRightControl.center;
    [self.carPasterView transformToFitQuadTopLeft:tl topRight:tr bottomLeft:bl bottomRight:br];

}

#pragma mark-

- (IBAction)scaleSliderValueChanged:(UISlider *)sender {
    CGFloat diff = sender.value - _lastSilderValue;
    _lastSilderValue = sender.value;
    CGFloat margin = kControlWidth / _preZoomScale;
    
    
    if (diff < 0) {
        if (self.bottomLeftControl.center.y - self.topLeftControl.center.y < margin ||
            self.bottomRightControl.center.y - self.topRightControl.center.y < margin ||
            self.topRightControl.center.x - self.topLeftControl.center.x < margin ||
            self.bottomRightControl.center.x - self.bottomLeftControl.center.x < margin) {
            return;
        }
    }
        
    CGFloat x = (_centerPoint.x - self.topLeftControl.center.x) * diff;
    CGFloat k = CGPointSlope(self.topLeftControl.center,_centerPoint);
    CGPoint tl = CGPointOffsetPoint(self.topLeftControl.center, -x, -x * k);

    x = (self.topRightControl.center.x - _centerPoint.x) * diff;
    k = CGPointSlope(self.topRightControl.center, _centerPoint);
    CGPoint tr = CGPointOffsetPoint(self.topRightControl.center, x, x*k);

    x = (_centerPoint.x - self.bottomLeftControl.center.x) * diff;
    k = CGPointSlope(self.bottomLeftControl.center,_centerPoint);
    CGPoint bl = CGPointOffsetPoint(self.bottomLeftControl.center, -x, -x * k);
    
    x = (self.bottomRightControl.center.x - _centerPoint.x) * diff;
    k = CGPointSlope(self.bottomRightControl.center, _centerPoint);
    CGPoint br = CGPointOffsetPoint(self.bottomRightControl.center, x, x * k);

    if (diff > 0) {
        CGFloat x1 = MIN(tl.x, bl.x),
        y1 = MIN(tl.y, tr.y),
        x2 = MAX(tr.x, br.x),
        y2 = MAX(bl.y, br.y);
        if (x2 - x1 > (CGRectGetWidth(_editImageView.bounds) - margin) ||
            y2 - y1 > (CGRectGetHeight(_editImageView.bounds) - margin)) {
            return;
        }
    }
    
    self.topLeftControl.center = tl;
    self.topRightControl.center = tr;
    self.bottomLeftControl.center = bl;
    self.bottomRightControl.center = br;
    [self updateTranform];
}

CGPoint CGPointOffsetPoint(CGPoint point, CGFloat x, CGFloat y) {
    CGPoint p;
    p.x = point.x + x;
    p.y = point.y + y;
    return p;
}

float CGPointSlope(CGPoint a, CGPoint b) {
    return (a.y - b.y ) / (a.x - b.x);
}

- (IBAction)scaleSliderEnd:(UISlider *)sender {
    _preZoomScale = _imageScrollView.zoomScale;
    sender.value = 1;
    _lastSilderValue = 1;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    _preZoomScale = scale;
}

- (void)updateControlScale:(CGFloat)scale {
    CGAffineTransform trans = CGAffineTransformMakeScale(scale, scale);
    self.topLeftControl.transform = trans;
    self.topRightControl.transform = trans;
    self.bottomRightControl.transform = trans;
    self.bottomLeftControl.transform = trans;
}

//缩放中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
//    NSLog(@">>>>scrollView:%f",scrollView.zoomScale);
    [self updateControlScale:1.0/scrollView.zoomScale];
    CGFloat diff_w = scrollView.bounds.size.width - scrollView.contentSize.width;
    CGFloat offsetX = diff_w > 0 ? diff_w * 0.5 : 0.0;
    
    CGFloat diff_h = scrollView.bounds.size.height - scrollView.contentSize.height;
    CGFloat offsetY = diff_h > 0 ? diff_h * 0.5 : 0.0;
    
    _editImageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                   scrollView.contentSize.height * 0.5 + offsetY);
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    if (!_carPasterView) {
        return nil;
    }
    return self.editImageView;
}

@end
